﻿using Abp.Domain.Repositories;
using Camc.Quality.Authorization.Roles;
using Camc.Quality.Bom;
using Camc.Quality.Bop;
using Camc.Quality.Common.CommonDate;
using Camc.Quality.DataDictionary;
using Camc.Quality.Materials;
using Camc.Quality.ProductionPlan;
using Camc.Quality.TrepanningManager.BomAnalyseDto;
using Camc.Quality.TrepanningManager.CollectBomDto;
using NUglify.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Camc.Quality.Common
{
    public class CommonAppService: QualityAppServiceBase
    {

        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly IRepository<MaterialsContent, Guid> _materialsContentRepository;
        private readonly IRepository<BomDesign, Guid> _bomDesignrepository;
        private readonly IRepository<BomDesignDetail, Guid> _bomDesignDetailrepository;
        private readonly IRepository<BopNode, Guid> _bopNodeRepository;
        private readonly IRepository<BopDesc, Guid> _bopDescRepository;
        private readonly IRepository<MakeTask, Guid> _makeTaskRepository;
        private readonly RoleManager _roleManager;
        public CommonAppService(IRepository<Sys_Code, Guid> sysCodeRepository, IRepository<MaterialsContent, Guid> materialsContentRepository, RoleManager roleManager,
            IRepository<BomDesign, Guid> bomDesignrepository, IRepository<BomDesignDetail, Guid> bomDesignDetailrepository, IRepository<BopNode, Guid> bopNodeRepository, IRepository<BopDesc, Guid> _bopDescRepositor,
            IRepository<MakeTask, Guid> makeTaskRepository
         )
        {
            this._sysCodeRepository = sysCodeRepository;
            this._materialsContentRepository = materialsContentRepository;
            this._bomDesignrepository = bomDesignrepository;
            this._bomDesignDetailrepository = bomDesignDetailrepository;
            this._bopNodeRepository = bopNodeRepository;
            this._roleManager = roleManager;
            this._bopDescRepository = _bopDescRepositor;
            _makeTaskRepository = makeTaskRepository;
        }
        /// <summary>
        /// 获取发次
        /// </summary>
        /// <returns></returns>
        public List<LabelCollection> GetLotNoList(Guid? ModelId = null)
        {
            List<LabelCollection> labelList = new List<LabelCollection>();
            labelList = GetLabelCollectionsByDes("发次");
            if (ModelId == null)
            {
                return labelList;
            }
            else
            {
                var makeModel = _makeTaskRepository.GetAll().Where(d => d.ModelId == ModelId);
                if (makeModel.Count() > 0)
                {
                    var modelIdList = makeModel.Select(d => d.LotNoId);

                    var query = (from cc in labelList
                                 join mm in modelIdList on cc.Value equals mm
                                 select cc).ToList();
                    if (query.Count > 0)
                    {
                        query = query.DistinctBy(d=>d.Value).OrderBy(d=>d.Label).ToList();
                    }
                    return query;
                }
                else
                {
                    return new List<LabelCollection> ();
                }
            }
        }

        /// <summary>
        /// 获取生产任务发次
        /// </summary>
        /// <returns></returns>
        public List<LabelCollection> GetLotMakeTaskNoList()
        {

            return GetLabelCollectionsByDes("发次");

        }
        /// <summary>
        /// 获取生产任务型号
        /// </summary>
        /// <returns></returns>
        public List<LabelCollection> GetModelList()
        {
            List<LabelCollection> collections = new List<LabelCollection>();
            var tempNode = _sysCodeRepository.FirstOrDefault(d => d.Description == "型号");
            if (tempNode != null)
            {
                collections = (from syscode in _sysCodeRepository.GetAll().Where(d => d.PPtr == tempNode.Id && d.IsUsed == 1)
                               join cc in _makeTaskRepository.GetAll() on syscode.Id equals cc.ModelId
                               select new LabelCollection
                               {
                                   Label = syscode.Description,
                                   Value = syscode.Id
                               }).ToList();
            }
            if (collections.Count > 0)
            {
                collections = collections.DistinctBy(d=>d.Value).OrderBy(d => d.Label).ToList();
            }
            return collections;
        }
        /// <summary>
        /// 获取生产任务型号
        /// </summary>
        /// <returns></returns>
        public List<LabelCollection> GetMakeTaskModelList()
        {
            return GetLabelCollectionsByDes("型号");
        }
        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        public List<LabelCollectInt> GetRoleList()
        {
            List<LabelCollectInt> collections = new List<LabelCollectInt>();
            var rolesList = _roleManager.Roles.ToList();
            if (rolesList != null)
            {
                collections = (from temp in rolesList
                               select new LabelCollectInt
                               {
                                   Label = temp.DisplayName,
                                   Value = temp.Id
                               }).ToList();
            }
            return collections;
        }
        public List<LabelCollectString> GetTypeList(string desc)
        {
            List<LabelCollectString> collections = new List<LabelCollectString>();
            var tempNode = _sysCodeRepository.FirstOrDefault(d => d.Description == desc);
            if (tempNode != null)
            {
                collections = (from syscode in _sysCodeRepository.GetAll().Where(d => d.PPtr == tempNode.Id && d.IsUsed == 1)
                               select new LabelCollectString
                               {
                                   Label = syscode.Description,
                                   Value = syscode.Description
                               }).ToList();
            }
            return collections;
        }
        public List<LabelCollection> GetLabelCollectionsByDes(string desc)
        {
            List<LabelCollection> collections = new List<LabelCollection>();
            var tempNode = _sysCodeRepository.FirstOrDefault(d => d.Description == desc);
            if (tempNode != null)
            {
                collections = (from syscode in _sysCodeRepository.GetAll().Where(d => d.PPtr == tempNode.Id&& d.IsUsed==1)
                               select new LabelCollection
                               {
                                   Label = syscode.Description,
                                   Value = syscode.Id
                               }).OrderBy(s => s.Label).ToList();
            }
            return collections;
        }
        /// <summary>
        /// 获取bom芯级
        /// </summary>
        /// <returns></returns>
        public async Task<List<LabelCollection>> GetBomXj(PublicEditDto publicEditDto)
        {
            //根据型号、发次 获取芯级
            var queryXjDatas = from queryXjData in _bomDesignrepository.GetAll().Where(t => t.SendTimeId == publicEditDto.SendTimeId && t.ModuleId == publicEditDto.ModuleId)
                               join queryBomDesignDetailData in _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == Guid.Empty && t.LevelNum == 2) on queryXjData.Id equals queryBomDesignDetailData.BomDesignId
                               join queryMaterialsData in _materialsContentRepository.GetAll() on queryBomDesignDetailData.MaterialId equals queryMaterialsData.Id
                               select new LabelCollection
                               {
                                   Label = queryMaterialsData.MaterialName + " " + queryMaterialsData.MaterialNo, //add 11/30
                                   Value = queryBomDesignDetailData.Id
                               };
            if (queryXjDatas.Count() > 0)
            {
                return queryXjDatas.ToList();
            }
            return new List<LabelCollection>();
        }
        /// <summary>
        /// 获取BOM部套
        /// </summary>
        /// <returns></returns>
        public async Task<List<LabelCollection>> GetBomBt(PublicEditDto bomChangeEditDto)
        {
            //根据型号、发次 、芯级 获取部套
            var queryXjList =  _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == bomChangeEditDto.XJId).Result;

            if (queryXjList != null)
            {
                var querybtData = from queryBomDesignDetailData in _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == queryXjList.Id)
                                  join queryMaterialsData in _materialsContentRepository.GetAll() on queryBomDesignDetailData.MaterialId equals queryMaterialsData.Id
                                  select new LabelCollection
                                  {
                                      Label = queryMaterialsData.MaterialName,
                                      Value = queryBomDesignDetailData.Id
                                  };
                if (querybtData.Count() > 0)
                {
                    return querybtData.ToList();
                }
            }
            return new List<LabelCollection>();
        }

        /// <summary>
        /// 获取BOM部套
        /// </summary>
        /// <returns></returns>
        public async Task<List<LabelCollection>> GetBomBtFb(PublicEditDto bomChangeEditDto)
        {
            //根据型号、发次 、芯级 获取部套
            var queryXjList = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == bomChangeEditDto.XJId).Result;

            if (queryXjList != null)
            {
                var querybtData = from queryBomDesignDetailData in _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == queryXjList.Id&& t.Status == DocumentStatus.已发布)
                                  join queryMaterialsData in _materialsContentRepository.GetAll() on queryBomDesignDetailData.MaterialId equals queryMaterialsData.Id
                                  select new LabelCollection
                                  {
                                      Label = queryMaterialsData.MaterialName,
                                      Value = queryBomDesignDetailData.Id
                                  };
                if (querybtData!=null&&querybtData.Count() > 0)
                {
                    return querybtData.ToList();
                }
            }
            return new List<LabelCollection>();
        }
        /// <summary>
        /// 获取bop芯级
        /// </summary>
        /// <returns></returns>
        public async Task<List<LabelCollection>> GetBopXj(PublicEditDto  publicEditDto)
        {
            //根据型号、发次 获取芯级
            var queryXjDatas =from queryDescData in _bopDescRepository.GetAll().Where(t=>t.ModelId == publicEditDto.ModuleId)
                              join queryXjData in _bopNodeRepository.GetAll() on queryDescData.Id equals queryXjData.ParentId
                              select new LabelCollection
                              {
                                  Label = queryXjData.NodeName,
                                  Value = queryXjData.Id
                              };
            if (queryXjDatas.Count() > 0)
            {
                return queryXjDatas.ToList();
            }
            return new List<LabelCollection>();
        }
        /// <summary>
        /// 获取bop部套
        /// </summary>
        /// <returns></returns>
        public async Task<List<LabelCollection>> GetBopBt(PublicEditDto  publicEditDto)
        {
            //根据型号、发次 获取芯级
            var queryXjDatas = from queryXjData in _bopNodeRepository.GetAll().Where(t => t.ParentId == publicEditDto.XJId && t.TechniqueEntityId != null)
                               select new LabelCollection
                               {
                                   Label = queryXjData.NodeName,
                                   Value = queryXjData.Id
                               };
            if (queryXjDatas.Count() > 0)
            {
                return queryXjDatas.ToList();
            }
            return new List<LabelCollection>();                                                                                            
        }

        //public  string AESDecrypt(string text, string password, string iv="")
        //{

        //    RijndaelManaged rijndaelCipher = new RijndaelManaged();
        //    rijndaelCipher.Mode = CipherMode.ECB;
        //    rijndaelCipher.Padding = PaddingMode.PKCS7;
        //    rijndaelCipher.KeySize = 128;
        //    rijndaelCipher.BlockSize = 128;
        //    byte[] encryptedData = Convert.FromBase64String(text);
        //    byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);
        //    byte[] keyBytes = new byte[16];
        //    int len = pwdBytes.Length;
        //    if (len > keyBytes.Length) len = keyBytes.Length;
        //    System.Array.Copy(pwdBytes, keyBytes, len);
        //    rijndaelCipher.Key = keyBytes;
        //    byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
        //    rijndaelCipher.IV = ivBytes;
        //    ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
        //    byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
        //    string mp= Encoding.UTF8.GetString(plainText);
        //    return mp;
        //}
        //解密算法
        public  string AesDecrypt(string str, string key)
        {
            try
            {
                if (string.IsNullOrEmpty(str)) return null;
                Byte[] toEncryptArray = Convert.FromBase64String(str);

                System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
                {
                    Key = Encoding.UTF8.GetBytes(key),
                    Mode = System.Security.Cryptography.CipherMode.ECB,
                    Padding = System.Security.Cryptography.PaddingMode.PKCS7
                };

                System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                return Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception ex)
            {

                return ex.Message;
            }
           
        }
        //加密算法算法
        public string AesEncrypt(string str, string key)
        {
            try
            {
                if (string.IsNullOrEmpty(str)) return null;
                Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);

                System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
                {
                    Key = Encoding.UTF8.GetBytes(key),
                    Mode = System.Security.Cryptography.CipherMode.ECB,
                    Padding = System.Security.Cryptography.PaddingMode.PKCS7
                };

                System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                return Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch (Exception ex)
            {

                return ex.Message;
            }
          
        }
    }
}

